<?php

/**
 * This is the model class for table "tbl_resources".
 *
 * The followings are the available columns in table 'tbl_resources':
 * @property integer $resources_id
 * @property string $fileName
 * @property string $fileType
 * @property integer $fileSize
 * @property integer $user_id
 * @property string $description
 * @property string $create_date
 * @property integer $status
 *
 * The followings are the available model relations:
 * @property TblUser $user
 * @property TblTeaching[] $tblTeachings
 */
class Resources extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Resources the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_resources';
    }
    public function download()
    {
        if(yii::app()->user->isGuest == 1)
        {
            yii::app()->controller->redirect(array('site/login'));
        }

        $fileUrl = $this->description.$this->fileName;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=".$this->fileName);
        if(readfile($fileUrl))
        {
            $this->download_count++;
            $this->save();
        }
    }
    /**
     * upload file to dir:$uploadDir
     * $fileName is the name of <input type="file" name="$fileName"/>
     * $ajax can choose the way of renturn the result
     * $description is the brief of this resource
     * @author : nonglei
     * @date   : 01/05/2014
     */
    public function upload($fileName, $uploadDir, $ajax)
    {
        $file = CUploadedFile :: getInstanceByName($fileName);

        if(is_null($file))
        {
            throw new CHttpException('Upload Error! None Of File');
        }

        if (is_object($file) && get_class($file) == 'CUploadedFile')
        {
            Yii::log("File Name : "  . $file->getName() );

            // 文件类型
            $this->fileType = strtolower($file->getExtensionName());

            // 存储文件名
            $newFileName = date('YmdHis') . '_' . rand(1000, 9999) . '.' . $this->fileType; 
            // 服务器端存储路径
            $newFilepath = $uploadDir . $newFileName;

            // 上传文件名
            $this->fileName = $newFileName;
            // 文件类型 （application/x-msdownload、application/pdf、application/octet-stream）
            $this->fileType = $file->getType();
            // 文件大小
            $this->fileSize = $file->getSize();

            $this->description = $uploadDir;

            $this->user_id = yii::app()->user->id;

            $this->status = 1;
            if ($file->saveAs($newFilepath) && $this->validate() &&
                $this->save())
            {
                // 将文件存在在服务器端
                $url = $uploadDir.$this->fileName;
                if($ajax == true)
                {
                    echo $url;
                }
                else
                {
                    return $url;
                }
            }
            else
            {
                throw new CHttpException('Upload Error! Can\'t save as server!');
            }

        }
        else
        {
            throw new CHttpException('Upload Error! Can\'t bult the Upload File');
        }
    }
    /**
     * upload file to dir:$uploadDir
     * $fileName is the name of <input type="file" name="$fileName"/>
     * $ajax can choose the way of renturn the result
     * $description is the brief of this resource
     * @author : nonglei
     * @date   : 01/05/2014
     */
    public function uploadReturnID($fileName, $uploadDir, $ajax)
    {
        $file = CUploadedFile :: getInstanceByName($fileName);

        if(is_null($file))
        {
            throw new CHttpException('Upload Error! None Of File');
        }

        if (is_object($file) && get_class($file) == 'CUploadedFile')
        {
            Yii::log("File Name : "  . $file->getName() );

            // 文件类型
            $this->fileType = strtolower($file->getExtensionName());

            // 存储文件名
            $newFileName = date('YmdHis') . '_' . rand(1000, 9999) . '.' . $this->fileType; 
            // 服务器端存储路径
            $newFilepath = $uploadDir . $newFileName;

            // 上传文件名
            $this->fileName = $newFileName;
            // 文件类型 （application/x-msdownload、application/pdf、application/octet-stream）
            $this->fileType = $file->getType();
            // 文件大小
            $this->fileSize = $file->getSize();

            $this->description = $uploadDir;

            $this->user_id = yii::app()->user->id;

            $this->status = 1;
            if ($file->saveAs($newFilepath) && $this->validate() &&
                $this->save())
            {
                // 将文件存在在服务器端
                $url = yii::app()->baseUrl.'/'.$uploadDir.$this->fileName;
                if($ajax == true)
                {
                    echo $url;
                }
                else
                {
                    return $this->resources_id;
                }
            }
            else
            {
                throw new CHttpException('Upload Error! Can\'t save as server!');
            }

        }
        else
        {
            throw new CHttpException('Upload Error! Can\'t bult the Upload File');
        }
    }
    /**
     * 删除系统上对应的资源
     *
     */
    public function deleteRealResources()
    {
        $fileUrl = $this->description.$this->fileName;
        if(file_exists($fileUrl))
        {
            unlink($fileUrl);
        }
    }
    /**
     * get the courseResource model of resources
     * @author : nonglei
     * @date   : 06/05/2014
     */
    public function getCourseResourceModel($course_id)
    {
        $model = CourseResources::model()->findByAttributes(array(
            'course_id'=>$course_id,
            'resources_id'=>$this->resources_id,
        ));
        return $model;
    }
    /**
     * get the teachingResource model of resources
     * @author : nonglei
     * @date   : 06/05/2014
     */
    public function getTeachingResourceModel($teaching_id)
    {
        $model = TeachingResources::model()->findByAttributes(array(
            'teaching_id'=>$teaching_id,
            'resources_id'=>$this->resources_id,
        ));
        return $model;
    }
    /**
     * @return array validation rules for model attributes.
     */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('fileName, fileType, fileSize, user_id, status', 'required'),
			array('fileSize, user_id, status', 'numerical', 'integerOnly'=>true),
			array('fileName', 'length', 'max'=>200),
			array('fileType', 'length', 'max'=>50),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('resources_id, fileName, fileType, fileSize, user_id, description, create_date, status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'user' => array(self::BELONGS_TO, 'User', 'user_id'),
			'tblTeachings' => array(self::MANY_MANY, 'Teaching', 'tbl_teaching_resources(resources_id, teaching_id)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'resources_id' => 'Resources',
			'fileName' => 'File Name',
			'fileType' => 'File Type',
			'fileSize' => 'File Size',
			'user_id' => 'User',
			'description' => 'Description',
			'create_date' => 'Create Date',
			'status' => 'Status',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('resources_id',$this->resources_id);
		$criteria->compare('fileName',$this->fileName,true);
		$criteria->compare('fileType',$this->fileType,true);
		$criteria->compare('fileSize',$this->fileSize);
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('create_date',$this->create_date,true);
		$criteria->compare('status',$this->status);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}
